package com.amoby.main.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.amoby.base.common.Constants;
import com.amoby.base.common.HttpUtils;
import com.amoby.base.common.Pager;
import com.amoby.base.utils.DateUtil;
import com.amoby.base.utils.JacksonBuilder;
import com.amoby.main.entity.AlipayOrder;
import com.amoby.main.entity.Business;
import com.amoby.main.entity.Cbabill;
import com.amoby.main.entity.PushSms;
import com.amoby.main.entity.PushSmsLog;
import com.amoby.main.mapper.AlipayOrderMapper;
import com.amoby.main.mapper.BusinessMapper;
import com.amoby.main.mapper.CbabillMapper;
import com.amoby.main.mapper.PushSmsLogMapper;
import com.amoby.main.mapper.PushSmsMapper;
import com.amoby.main.service.PushSmsService;
import com.amoby.main.service.SmsService;

/**
 * <p>Title：PushSmsServiceImpl</p>
 * <p>Desc：</p>
 * @address http://www.yingmob.com/
 * @author zhaoyy
 * @date 2016-2-26 上午11:55:59
 */
@Service
public class PushSmsServiceImpl implements PushSmsService{
    private static Log          logger    = LogFactory.getLog(PushSmsServiceImpl.class);
    @Autowired
    private PushSmsLogMapper    pushSmsLogMapper;
    @Autowired
    private PushSmsMapper       pushSmsMapper;
    @Autowired
    private AlipayOrderMapper   alipayOrderMapper;
    @Autowired
    private BusinessMapper      businessMapper;
    @Autowired
    private SmsService          smsService;
    @Autowired
    private CbabillMapper         cbabillMapper;
    
    /**
     * 谷歌短信推送入口
     * @author Lasing 2016-2-26 上午11:22:45
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public boolean smspush(String phone, String orderNo, String content, int type) {
        //content = content.substring(0, 60);
        HttpUtils httpUtils = HttpUtils.getInstance();
        String url = "https://api.parse.com/1/push";
        List<Header> headers = new ArrayList<Header>();
        //测试的key
        Header header1 = new BasicHeader("X-Parse-Application-Id", Constants.PUSH_APPLICATION_ID);
        Header header2 = new BasicHeader("X-Parse-REST-API-Key", Constants.PUSH_REST_API_KEY);
        logger.debug("正式的key==="+Constants.PUSH_APPLICATION_ID +"=================="+Constants.PUSH_REST_API_KEY);
        //正式的key
//        Header header1 = new BasicHeader("X-Parse-Application-Id", "MShvDdh1gJ3Eu63RRqpi8VfeKS6VUyYAsz0s8Drx");
//        Header header2 = new BasicHeader("X-Parse-REST-API-Key", "hpMBP2sHGIqKpk7c6UfZbs3TYUdV2O3ivLPZ6IvT");
        headers.add(header1);
        headers.add(header2);
        /* {"where":{"deviceType": "android"},"data":
         *   {"action": "com.wyhd.sms.action",  
         *    "orderId": "62014534532333", 
         *    "phone": "8618716664540|8618734432232",
         *    "message": "你有一笔消费￥49",
         *    "type": 1 }}
         */
        String json = "{\"where\":{\"deviceType\":\"android\"},\"data\":{\"action\":\"" + Constants.SMS_PUSH_ACTION + "\",\"orderId\":\"" + orderNo + "\",\"phone\":\"" 
                + phone + "\",\"message\":\"" + content + "\",\"type\":" + type + "}}";
        logger.debug("向app推送短信发送内容========="+json);
        try {
            String result = httpUtils.httpPost(url, headers, json, false);
            Map<String, Object> map = JacksonBuilder.mapper().readValue(result, Map.class);
            logger.debug("返回json:" + result);
            return map.get("result").equals(true);
        } catch (Exception e) {
            logger.error("请求推送服务器异常", e);
            return false;
        }
    }

    
    
    public static void main(String[] args) {
        HttpUtils httpUtils = HttpUtils.getInstance();
        String url = "https://api.parse.com/1/push";
        List<Header> headers = new ArrayList<Header>();
        //测试的key
//        Header header1 = new BasicHeader("X-Parse-Application-Id", Constants.PUSH_APPLICATION_ID);
//        Header header2 = new BasicHeader("X-Parse-REST-API-Key", Constants.PUSH_REST_API_KEY);
        //正式的key
        Header header1 = new BasicHeader("X-Parse-Application-Id", "MShvDdh1gJ3Eu63RRqpi8VfeKS6VUyYAsz0s8Drx");
        Header header2 = new BasicHeader("X-Parse-REST-API-Key", "hpMBP2sHGIqKpk7c6UfZbs3TYUdV2O3ivLPZ6IvT");
        headers.add(header1);
        headers.add(header2);
        /* {"where":{"deviceType": "android"},"data":
         *   {"action": "com.wyhd.sms.action",  
         *    "orderId": "62014534532333", 
         *    "phone": "8618716664540|8618734432232",
         *    "message": "你有一笔消费￥49",
         *    "type": 1 }}
         */
        
        String json = "{\"where\":{\"deviceType\":\"android\"},\"data\":{\"action\":\"com.wyhd.sms.action\",\"orderId\":\"TY111466996377070268\",\"phone\":\"0450986889|0433568521\",\"message\":\"[0268] The payment amount of $295.69 has been processed successfully http://mmobile.supaytech.com.au/ .【PAYBANG】\",\"type\":1}}";

        //String aaa = "15625104360";
        //String json = "{\"where\":{\"deviceType\":\"android\"},\"data\":{\"action\":\"" + Constants.SMS_PUSH_ACTION + "\",\"orderId\":\"" + 123 + "\",\"phone\":\""  + aaa + "\",\"message\":\"" + "ssssssssss" + "\",\"type\":" + 1 + "}}";
        logger.debug("向app推送短信发送内容========="+json);
        try {
            String result = httpUtils.httpPost(url, headers, json, false);
            Map<String, Object> map = JacksonBuilder.mapper().readValue(result, Map.class);
            logger.debug("返回json:" + result);
            System.err.println(map.get("result").equals(true)); ;
        } catch (Exception e) {
            logger.error("请求推送服务器异常", e);
        }
    }
    /**
     * 修改短信推送时间
     */
    @Override
    public int updPushSmsLogTimeAndStatus(String orderId, int type, String pushTime) {
        Map<String, Object> map = new HashMap<String, Object>();
        int count =0;
        if(type==1){ //交易短信
            map.put("orderNo", orderId);
            map.put("dealpushReveTime", pushTime);
            map.put("dealpushStatus", 1);
            count = pushSmsLogMapper.updDtimeAndStatus(map);
        }else{ //转账短信
            //转账时先根据转账id查询出对应的订单
            map.put("billId", orderId);
            List<PushSmsLog> smslog = pushSmsLogMapper.getPushSmsLog(map);
            for (int i = 0; i < smslog.size(); i++) {
                map.clear();
                map.put("orderNo", smslog.get(i).getOrderNo());
                map.put("transferpushReveTime", pushTime);
                map.put("transferpushStatus", 1);
                pushSmsLogMapper.updTtimeAndStatus(map);
                count++;
            }
        }
        return count;
    }

    /**
     * 保存短信发送
     */
    @Override
    public int addSendSms(String orderId, String phone, int type, String sendTime, int status) {
        Map<String, Object> map = new HashMap<String, Object>();
        int count =0;
        if(type==1 && (phone!=null && !"".equals(phone))){ //交易短信
            map.put("orderNo", orderId);   //订单号
            map.put("phone", phone);
            map.put("type", type);
            PushSms osms = pushSmsMapper.selectPushSms(map); //条件查询短信信息
            if(osms==null){  //如果为空则新增保存
                PushSms sms = new PushSms();
                sms.setOrderNo(orderId);
                sms.setType(type);
                sms.setStatus(status);
                sms.setSendTime(DateUtil.paseDatetime(sendTime));
                sms.setPhone(phone);
                count = pushSmsMapper.insertSelective(sms);
            }else{
                osms.setSendTime(DateUtil.paseDatetime(sendTime));  //更新发送时间
                osms.setStatus(status);
                pushSmsMapper.updateByPrimaryKey(osms);   //更新短信发送信息
            }
            // 根据订单号查询短信信息来修改交易短信发送情况
            map.clear();
            map.put("orderNo", orderId);
            map.put("type", type);
            List<PushSms> sms = pushSmsMapper.getPushsSmsByOrderNoAndType(map);//查询短信发送信息
            int num = 0;
            for (int i = 0; i < sms.size(); i++) {
                if(sms.get(i).getStatus()==1){
                    num++;
                }
            }
            //根据订单号查询商家id
            int counts = 0;
            Business business = businessMapper.selectBusinessByOrderNo(orderId);
            logger.debug("orderId==========="+orderId  +"========="+business);
            if(business!=null&&business.getPhone2() != null && !"".equals(business.getPhone2()) && !"".equals(business.getShopName())&& business.getShopName() != null) {
                counts ++;
                if (StringUtils.isNotEmpty(business.getPhone3())) {// 大陆商家
                    counts ++;
                    if (StringUtils.isNotEmpty(business.getPhone4())) {
                        counts ++;
                    }
                    if (StringUtils.isNotEmpty(business.getPhone5())) {
                        counts ++;
                    }
                }
            }
            if(counts==num){ //判断是否发送成功  同时修改交易短信发送情况  全部完成
                map.clear();
                map.put("orderNo", orderId);
                map.put("dealSmsStatus", 2);
                pushSmsLogMapper.updDealSmsStatus(map);
            }else if(num!=0 && counts>num){ //部分完成
                map.clear();
                map.put("orderNo", orderId);
                map.put("dealSmsStatus", 1);
                pushSmsLogMapper.updDealSmsStatus(map);
            }else if(num==0 && counts>0){ //全部失败
                map.clear();
                map.put("orderNo", orderId);
                map.put("dealSmsStatus", 3);
                pushSmsLogMapper.updDealSmsStatus(map);
            }
        }else if(type==2 && (phone!=null && !"".equals(phone))){ //转账短信
            map.clear();
            map.put("billId", orderId);   
            //根据转账id查询短信日志
            List<PushSmsLog> smslog = pushSmsLogMapper.getPushSmsLog(map);
          //根据订单号查询商家id
            int counts = 0;
            Business business = businessMapper.selectBusinessByOrderNo(smslog.get(0).getOrderNo());
            if(business!=null && business.getPhone2() != null && !"".equals(business.getPhone2()) && !"".equals(business.getShopName())&& business.getShopName() != null) {
                counts ++;
                if (StringUtils.isNotEmpty(business.getPhone3())) {// 大陆商家
                    counts ++;
                    if (StringUtils.isNotEmpty(business.getPhone4())) {
                        counts ++;
                    }
                    if (StringUtils.isNotEmpty(business.getPhone5())) {
                        counts ++;
                    }
                }
            }
            for (int i = 0; i < smslog.size(); i++) {
                map.clear();
                map.put("orderNo", smslog.get(i).getOrderNo());   //订单号
                map.put("phone", phone);
                map.put("type", type);
                PushSms osms = pushSmsMapper.selectPushSms(map);//条件查询短信信息
                if(osms==null){  //如果为空则新增保存
                    PushSms sms = new PushSms();
                    sms.setOrderNo(smslog.get(i).getOrderNo());
                    sms.setType(type);
                    sms.setStatus(status);
                    sms.setSendTime(DateUtil.paseDatetime(sendTime));
                    sms.setPhone(phone);
                    sms.setBillId(orderId);
                    count = pushSmsMapper.insertSelective(sms);
                }else{
                    osms.setSendTime(DateUtil.paseDatetime(sendTime));  //更新发送时间
                    osms.setStatus(status);
                    pushSmsMapper.updateByPrimaryKey(osms);   //更新短信发送信息
                }
                // 根据订单号查询短信信息来修改转账短信发送情况
                map.clear();
                map.put("orderNo", smslog.get(i).getOrderNo());
                map.put("type", type);
                List<PushSms> sms = pushSmsMapper.getPushsSmsByOrderNoAndType(map);//查询短信发送信息
                int num = 0;
                for (int j = 0; j < sms.size(); j++) {
                    if(sms.get(j).getStatus()==1){
                        num++;
                    }
                }
                if(counts==num){ //判断是否发送成功  同时修改交易短信发送情况  全部完成
                    map.clear();
                    map.put("orderNo", smslog.get(i).getOrderNo());
                    map.put("transferSmsStatus", 2);
                    pushSmsLogMapper.updTSmsStatus(map);
                }else if(num!=0 && counts>num){ //部分完成
                    map.clear();
                    map.put("orderNo", smslog.get(i).getOrderNo());
                    map.put("transferSmsStatus", 1);
                    pushSmsLogMapper.updTSmsStatus(map);
                }else if(num==0 && counts>0){ //全部失败
                    map.clear();
                    map.put("orderNo", smslog.get(i).getOrderNo());
                    map.put("transferSmsStatus", 3);
                    pushSmsLogMapper.updTSmsStatus(map);
                }
            }
        }
        return count;
    }

    /**
     * 修改短信接收
     */
    @Override
    public int updSendSms(String orderId, String phone, int type, String successTime) {
        Map<String, Object> map = new HashMap<String, Object>();
        int count =0;
        if(type==1 && (phone!=null && !"".equals(phone))){ //交易短信
            map.put("orderNo", orderId);
            map.put("phone", phone);
            map.put("type", type);
            map.put("successTime", successTime);
            count = pushSmsMapper.updStimeAndStatus(map);
        }else if(type==2 && (phone!=null && !"".equals(phone))){ //转账短信
            map.put("billId", orderId);
            List<PushSmsLog> smslog = pushSmsLogMapper.getPushSmsLog(map);
            for (int i = 0; i < smslog.size(); i++) {
                map.clear();
                map.put("orderNo", smslog.get(i).getOrderNo());
                map.put("phone", phone);
                map.put("type", type);
                map.put("successTime", successTime);
                pushSmsMapper.updStimeAndStatus(map);
                count++;
            }
        }
        return count;
    }

    /**
     * 分页获取短信日志
     */
    @Override
    public Pager queryPage(Pager pager) {
        pager.setResult(pushSmsLogMapper.selectPager(pager)); 
        return pager;
    }

    /**
     * 分页获取短信详情
     */
    @Override
    public Pager querySmsPager(Pager pager) {
        pager.setResult(pushSmsMapper.selectSmsPager(pager)); 
        return pager;
    }

    /**
     * 每5分钟定时检查交易短信发送失败进行第三方平台发送===========
     */
    @Override
    public void pushDealOrdersTask() {
        logger.debug("交易短信定时任务执行了=============================================");
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("searchTime", DateUtil.getTwoMinute());
            // 1、 查询支付时间小于当前2分钟之前的短信发送失败的订单
            List<PushSmsLog> smslog = pushSmsLogMapper.selectSmsLogList(map);
            if (smslog.size() > 0) {   // 有发送失败的订单
                for (PushSmsLog smsl : smslog) {
                    // 1.1根据订单号查询订单
                    AlipayOrder ao = alipayOrderMapper.selectAlipayOrderByNo(smsl.getOrderNo());
                    // 1.2查询商家信息
                    Business business = businessMapper.selectByPrimaryKey(ao.getBsId());
                    if (smsl.getDealSmsStatus() != 1) {  // 如果不是部分完成则全部重新发送
                        logger.debug("交易短信发送失败，全部重新发送=======================");
                        // 短信平台发送短信=============================================
                        if (business != null) {
                            // 1.3第三方平台方式短信
                            String code = ao.getOrderNo().substring(ao.getOrderNo().length() - 4);// 验证码
                            Double amount = ao.getAmount();// 消费金额
                            if (business.getPhone() != null && !"".equals(business.getPhone()) && !"".equals(business.getShopName())
                                    && business.getShopName() != null) {
                                String content = "[" + code + "]" + " The payment amount of $" + amount
                                        + " has been processed successfully http://mmobile.e-swipe.com.au/ ." + Constants.SMS_LAST_STR;
                                smsService.sendBatchEventMessage(business.getPhone(), business.getPhone2(), business.getPhone3(), business.getPhone4(),
                                        business.getPhone5(), content);
                                logger.debug("短信发送内容=====================================" + content);
                                // 1.4短信发送成功修改对应的短信发送情况信息
                                smsl.setDealpushStatus(1); // 推送转账改为成功
                                smsl.setDealSmsStatus(2);  // 短信发送情况全部完成
                                pushSmsLogMapper.updateByPrimaryKey(smsl);
                                if (business.getPhone2() != null && !"".equals(business.getPhone2())) {
                                    map.clear();
                                    map.put("orderNo", smsl.getOrderNo());   // 订单号
                                    map.put("phone", business.getPhone2());
                                    map.put("type", 1);  // 交易短信
                                    PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                    if (osms == null) {  // 如果为空则新增保存
                                        PushSms sms = new PushSms();
                                        sms.setOrderNo(smsl.getOrderNo());
                                        sms.setType(1);
                                        sms.setStatus(1);
                                        sms.setSendTime(new Date());
                                        sms.setPhone(business.getPhone2());
                                        pushSmsMapper.insertSelective(sms);
                                    } else {
                                        osms.setSendTime(new Date());  // 更新发送时间
                                        osms.setStatus(1);
                                        pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                    }
                                }
                                if (business.getPhone3() != null && !"".equals(business.getPhone3())) {
                                    map.clear();
                                    map.put("orderNo", smsl.getOrderNo());   // 订单号
                                    map.put("phone", business.getPhone3());
                                    map.put("type", 1);  // 交易短信
                                    PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                    if (osms == null) {  // 如果为空则新增保存
                                        PushSms sms = new PushSms();
                                        sms.setOrderNo(smsl.getOrderNo());
                                        sms.setType(1);
                                        sms.setStatus(1);
                                        sms.setSendTime(new Date());
                                        sms.setPhone(business.getPhone3());
                                        pushSmsMapper.insertSelective(sms);
                                    } else {
                                        osms.setSendTime(new Date());  // 更新发送时间
                                        osms.setStatus(1);
                                        pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                    }
                                }
                                if (business.getPhone4() != null && !"".equals(business.getPhone4())) {
                                    map.clear();
                                    map.put("orderNo", smsl.getOrderNo());   // 订单号
                                    map.put("phone", business.getPhone4());
                                    map.put("type", 1);  // 交易短信
                                    PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                    if (osms == null) {  // 如果为空则新增保存
                                        PushSms sms = new PushSms();
                                        sms.setOrderNo(smsl.getOrderNo());
                                        sms.setType(1);
                                        sms.setStatus(1);
                                        sms.setSendTime(new Date());
                                        sms.setPhone(business.getPhone4());
                                        pushSmsMapper.insertSelective(sms);
                                    } else {
                                        osms.setSendTime(new Date());  // 更新发送时间
                                        osms.setStatus(1);
                                        pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                    }
                                }
                                if (business.getPhone5() != null && !"".equals(business.getPhone5())) {
                                    map.clear();
                                    map.put("orderNo", smsl.getOrderNo());   // 订单号
                                    map.put("phone", business.getPhone5());
                                    map.put("type", 1);  // 交易短信
                                    PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                    if (osms == null) {  // 如果为空则新增保存
                                        PushSms sms = new PushSms();
                                        sms.setOrderNo(smsl.getOrderNo());
                                        sms.setType(1);
                                        sms.setStatus(1);
                                        sms.setSendTime(new Date());
                                        sms.setPhone(business.getPhone5());
                                        pushSmsMapper.insertSelective(sms);
                                    } else {
                                        osms.setSendTime(new Date());  // 更新发送时间
                                        osms.setStatus(1);
                                        pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                    }
                                }
                            }
                        }
                        // 短信平台发送短信=============================================
                    } else { // 部分发送成功 则发送失败的号码
                        logger.debug("部分推送成功，则只推送失败的号码========================");
                        map.clear();
                        map.put("orderNo", smsl.getOrderNo());
                        map.put("type", 1);
                        // 1.5查询短信发送信息
                        List<PushSms> sms = pushSmsMapper.getPushsSmsByOrderNoAndType(map);
                        // 1.6获取商家的所有手机号和手机号的数量
                        String[] phones = {};
                        if (business.getPhone2() != null && !"".equals(business.getPhone2()) && !"".equals(business.getShopName())
                                && business.getShopName() != null) {
                            phones = insert(phones, business.getPhone2());
                            if (StringUtils.isNotEmpty(business.getPhone3())) {// 大陆商家
                                phones = insert(phones, business.getPhone3());
                                if (StringUtils.isNotEmpty(business.getPhone4())) {
                                    phones = insert(phones, business.getPhone4());
                                }
                                if (StringUtils.isNotEmpty(business.getPhone5())) {
                                    phones = insert(phones, business.getPhone5());
                                }
                            }
                        }
                        String sendPhone = "";
                        String[] phone = {};
                        StringBuffer sb = new StringBuffer();
                        if (sms.size() > 0) {
                            for (int i = 0; i < sms.size(); i++) {
                                if (sms.get(i).getStatus() == 1) {  // 成功的
                                    phone = insert(phone, sms.get(i).getPhone());
                                    logger.debug("已发送成功的号码=================" + sms.get(i).getPhone());
                                }
                            }
                            // 对比前需要对数组进行排序
                            Arrays.sort(phones);
                            Arrays.sort(phone);
                            for (String str : phones) {
                                if (Arrays.binarySearch(phone, str) < 0) {
                                    logger.debug("未发送成功的号码=================" + str);
                                    sb.append(str + "#");
                                }
                            }
                            // 发送的号码
                            if (sb.length() > 0) {
                                sendPhone = sb.toString();
                                sendPhone = sendPhone.substring(0, sendPhone.length() - 1);
                            }
                            // 发送失败的号码判断
                            if (!"".equals(sendPhone)) {
                                // 短信平台发送短信=============================================
                                String code = ao.getOrderNo().substring(ao.getOrderNo().length() - 4);// 验证码
                                Double amount = ao.getAmount();// 消费金额
                                String content = "[" + code + "]" + " The payment amount of $" + amount
                                        + " has been processed successfully http://mmobile.e-swipe.com.au/ ." + Constants.SMS_LAST_STR;
                                if (sendPhone.contains("#")) {
                                    String sendphone[] = sendPhone.split("#");
                                    if (sendphone.length == 2) {
                                        smsService.sendBatchEventMessage(sendphone[0], sendphone[0], sendphone[1], null, null, content);
                                        //修改短信发送情况和短信详情信息
                                        smsl.setDealpushStatus(1); // 推送转账改为成功
                                        smsl.setDealSmsStatus(2);  // 短信发送情况全部完成
                                        pushSmsLogMapper.updateByPrimaryKey(smsl);
                                        for (int i = 0; i < sendphone.length; i++) {
                                            map.clear();
                                            map.put("orderNo", smsl.getOrderNo());   // 订单号
                                            map.put("phone", sendphone[i]);
                                            map.put("type", 1);  // 交易短信
                                            PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                            if (osms == null) {  // 如果为空则新增保存
                                                PushSms sm = new PushSms();
                                                sm.setOrderNo(smsl.getOrderNo());
                                                sm.setType(1);
                                                sm.setStatus(1);
                                                sm.setSendTime(new Date());
                                                sm.setPhone(sendphone[i]);
                                                pushSmsMapper.insertSelective(sm);
                                            } else {
                                                osms.setSendTime(new Date());  // 更新发送时间
                                                osms.setStatus(1);
                                                pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                            }
                                        }
                                    } else if (sendphone.length == 3) {
                                        smsService.sendBatchEventMessage(sendphone[0], sendphone[0], sendphone[1], sendphone[2], null, content);
                                        //修改短信发送情况和短信详情信息
                                        smsl.setDealpushStatus(1); // 推送转账改为成功
                                        smsl.setDealSmsStatus(2);  // 短信发送情况全部完成
                                        pushSmsLogMapper.updateByPrimaryKey(smsl);
                                        for (int i = 0; i < sendphone.length; i++) {
                                            map.clear();
                                            map.put("orderNo", smsl.getOrderNo());   // 订单号
                                            map.put("phone", sendphone[i]);
                                            map.put("type", 1);  // 交易短信
                                            PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                            if (osms == null) {  // 如果为空则新增保存
                                                PushSms sm = new PushSms();
                                                sm.setOrderNo(smsl.getOrderNo());
                                                sm.setType(1);
                                                sm.setStatus(1);
                                                sm.setSendTime(new Date());
                                                sm.setPhone(sendphone[i]);
                                                pushSmsMapper.insertSelective(sm);
                                            } else {
                                                osms.setSendTime(new Date());  // 更新发送时间
                                                osms.setStatus(1);
                                                pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                            }
                                        }
                                    } else if (sendphone.length == 4) {
                                        smsService.sendBatchEventMessage(sendphone[0], sendphone[0], sendphone[1], sendphone[2], sendphone[3], content);
                                        //修改短信发送情况和短信详情信息
                                        smsl.setDealpushStatus(1); // 推送转账改为成功
                                        smsl.setDealSmsStatus(2);  // 短信发送情况全部完成
                                        pushSmsLogMapper.updateByPrimaryKey(smsl);
                                        for (int i = 0; i < sendphone.length; i++) {
                                            map.clear();
                                            map.put("orderNo", smsl.getOrderNo());   // 订单号
                                            map.put("phone", sendphone[i]);
                                            map.put("type", 1);  // 交易短信
                                            PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                            if (osms == null) {  // 如果为空则新增保存
                                                PushSms sm = new PushSms();
                                                sm.setOrderNo(smsl.getOrderNo());
                                                sm.setType(1);
                                                sm.setStatus(1);
                                                sm.setSendTime(new Date());
                                                sm.setPhone(sendphone[i]);
                                                pushSmsMapper.insertSelective(sm);
                                            } else {
                                                osms.setSendTime(new Date());  // 更新发送时间
                                                osms.setStatus(1);
                                                pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                            }
                                        }
                                    }
                                } else {
                                    smsService.sendBatchEventMessage(sendPhone, sendPhone, null, null, null, content);
                                    //修改短信发送情况和短信详情信息
                                    smsl.setDealpushStatus(1); // 推送转账改为成功
                                    smsl.setDealSmsStatus(2);  // 短信发送情况全部完成
                                    pushSmsLogMapper.updateByPrimaryKey(smsl);
                                    map.clear();
                                    map.put("orderNo", smsl.getOrderNo());   // 订单号
                                    map.put("phone", sendPhone);
                                    map.put("type", 1);  // 交易短信
                                    PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                    if (osms == null) {  // 如果为空则新增保存
                                        PushSms sm = new PushSms();
                                        sm.setOrderNo(smsl.getOrderNo());
                                        sm.setType(1);
                                        sm.setStatus(1);
                                        sm.setSendTime(new Date());
                                        sm.setPhone(sendPhone);
                                        pushSmsMapper.insertSelective(sm);
                                    } else {
                                        osms.setSendTime(new Date());  // 更新发送时间
                                        osms.setStatus(1);
                                        pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                    }
                                }
                                logger.debug("短信发送内容=====================================" + content);
                                // 短信平台发送短信=============================================
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("交易定时任务失败=======",e);
        }
    }

    /**
     * 凌晨1点30分检查转账短信发送失败的进行第三方平台发送===========
     */
    @Override
    public void pushTransferOrdersTask() {
        logger.debug("转账短信定时任务执行了=============================================");
        try {
            //1、根据订单号查询短信日志推送情况和短信发送情况
            Map<String, Object> map = new HashMap<String, Object>();
            //根据账单id分组
            List<PushSmsLog> smslogList = pushSmsLogMapper.selectPushSmsLogList();
            if(smslogList.size()>0){
                for (PushSmsLog smsl:smslogList) {
                    //1.1根据订单号查询订单信息
                    AlipayOrder ao = alipayOrderMapper.selectAlipayOrderByNo(smsl.getOrderNo());
                    //1.2查询商家信息
                    Business business = businessMapper.selectByPrimaryKey(ao.getBsId());
                    if (smsl.getTransferSmsStatus() != 1) {  // 如果不是部分完成则全部重新发送
                        logger.debug("转账短信发送失败，全部重新发送====================");
                        // 短信平台发送短信=============================================
                        if (business != null) {
                            // 1.3第三方平台方式短信
                            // 1.3.1根据转账id查询转账金额
                            Cbabill bill = cbabillMapper.selectByPrimaryKey(Long.parseLong(smsl.getBillId()));
                            Double amount = bill.getAmount();   //转账金额
                            if (business.getPhone() != null && !"".equals(business.getPhone()) && !"".equals(business.getShopName())
                                    && business.getShopName() != null) {
                                String content = "[" + business.getShopName() + "]" + " Please be advised you have AU $" + amount
                                        + " through CBA transfer to your,please check. http://mmobile.e-swipe.com.au/ . " + Constants.SMS_LAST_STR;
                                smsService.sendBatchEventMessage(business.getPhone(), business.getPhone2(), business.getPhone3(), business.getPhone4(),
                                        business.getPhone5(), content);
                                logger.debug("短信发送内容=====================================" + content);
                                //1.4根据转账id查询全部短信日志
                                map.put("billId", smsl.getBillId());
                                List<PushSmsLog> smslogl = pushSmsLogMapper.getPushSmsLog(map); 
                                // 1.5短信发送成功修改对应的短信发送情况信息
                                for(PushSmsLog pushsms:smslogl){
                                    pushsms.setTransferpushStatus(1); // 推送转账改为成功
                                    pushsms.setTransferSmsStatus(2);  // 短信发送情况全部完成
                                    pushSmsLogMapper.updateByPrimaryKey(pushsms);
                                    if (business.getPhone2() != null && !"".equals(business.getPhone2())) {
                                        map.clear();
                                        map.put("orderNo", pushsms.getOrderNo());   // 订单号
                                        map.put("phone", business.getPhone2());
                                        map.put("type", 2);  // 转账短信
                                        PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                        if (osms == null) {  // 如果为空则新增保存
                                            PushSms sms = new PushSms();
                                            sms.setOrderNo(pushsms.getOrderNo());
                                            sms.setType(2);
                                            sms.setStatus(1);
                                            sms.setSendTime(new Date());
                                            sms.setBillId(smsl.getBillId());
                                            sms.setPhone(business.getPhone2());
                                            pushSmsMapper.insertSelective(sms);
                                        } else {
                                            osms.setSendTime(new Date());  // 更新发送时间
                                            osms.setStatus(1);
                                            pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                        }
                                    }
                                    if (business.getPhone3() != null && !"".equals(business.getPhone3())) {
                                        map.clear();
                                        map.put("orderNo", pushsms.getOrderNo());   // 订单号
                                        map.put("phone", business.getPhone3());
                                        map.put("type", 2);  // 转账短信
                                        PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                        if (osms == null) {  // 如果为空则新增保存
                                            PushSms sms = new PushSms();
                                            sms.setOrderNo(pushsms.getOrderNo());
                                            sms.setType(2);
                                            sms.setStatus(1);
                                            sms.setSendTime(new Date());
                                            sms.setBillId(smsl.getBillId());
                                            sms.setPhone(business.getPhone3());
                                            pushSmsMapper.insertSelective(sms);
                                        } else {
                                            osms.setSendTime(new Date());  // 更新发送时间
                                            osms.setStatus(1);
                                            pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                        }
                                    }
                                    if (business.getPhone4() != null && !"".equals(business.getPhone4())) {
                                        map.clear();
                                        map.put("orderNo", pushsms.getOrderNo());   // 订单号
                                        map.put("phone", business.getPhone4());
                                        map.put("type", 2);  // 转账短信
                                        PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                        if (osms == null) {  // 如果为空则新增保存
                                            PushSms sms = new PushSms();
                                            sms.setOrderNo(pushsms.getOrderNo());
                                            sms.setType(2);
                                            sms.setStatus(1);
                                            sms.setSendTime(new Date());
                                            sms.setBillId(smsl.getBillId());
                                            sms.setPhone(business.getPhone4());
                                            pushSmsMapper.insertSelective(sms);
                                        } else {
                                            osms.setSendTime(new Date());  // 更新发送时间
                                            osms.setStatus(1);
                                            pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                        }
                                    }
                                    if (business.getPhone5() != null && !"".equals(business.getPhone5())) {
                                        map.clear();
                                        map.put("orderNo", pushsms.getOrderNo());   // 订单号
                                        map.put("phone", business.getPhone5());
                                        map.put("type", 2);  // 转账短信
                                        PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                        if (osms == null) {  // 如果为空则新增保存
                                            PushSms sms = new PushSms();
                                            sms.setOrderNo(pushsms.getOrderNo());
                                            sms.setType(2);
                                            sms.setStatus(1);
                                            sms.setSendTime(new Date());
                                            sms.setBillId(smsl.getBillId());
                                            sms.setPhone(business.getPhone5());
                                            pushSmsMapper.insertSelective(sms);
                                        } else {
                                            osms.setSendTime(new Date());  // 更新发送时间
                                            osms.setStatus(1);
                                            pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                        }
                                    }
                                }
                            }
                        }
                        // 短信平台发送短信=============================================
                    } else { // 部分发送成功 则发送失败的号码
                        logger.debug("转账部分发送成功 则发送失败的号码=====================");
                        //1.1根据转账id查询推送日志
                        map.clear();
                        map.put("billId", smsl.getBillId());
                        List<PushSmsLog> smslogl = pushSmsLogMapper.getPushSmsLog(map);
                        map.clear();
                        map.put("orderNo", smslogl.get(0).getOrderNo());
                        map.put("type", 2);
                        // 1.2查询短信发送信息
                        List<PushSms> sms = pushSmsMapper.getPushsSmsByOrderNoAndType(map);
                        // 1.6获取商家的所有手机号和手机号的数量
                        String[] phones = {};
                        if (business.getPhone2() != null && !"".equals(business.getPhone2()) && !"".equals(business.getShopName())
                                && business.getShopName() != null) {
                            phones = insert(phones, business.getPhone2());
                            if (StringUtils.isNotEmpty(business.getPhone3())) {// 大陆商家
                                phones = insert(phones, business.getPhone3());
                                if (StringUtils.isNotEmpty(business.getPhone4())) {
                                    phones = insert(phones, business.getPhone4());
                                }
                                if (StringUtils.isNotEmpty(business.getPhone5())) {
                                    phones = insert(phones, business.getPhone5());
                                }
                            }
                        }
                        logger.debug("部分推送成功，则只推送失败的号码========================");
                        String sendPhone = "";
                        String[] phone = {};
                        StringBuffer sb = new StringBuffer();
                        if (sms.size() > 0) {
                            for (int i = 0; i < sms.size(); i++) {
                                if (sms.get(i).getStatus() == 1) {  // 成功的
                                    phone = insert(phone, sms.get(i).getPhone());
                                    logger.debug("已发送成功的号码=================" + sms.get(i).getPhone());
                                }
                            }
                            // 对比前需要对数组进行排序
                            Arrays.sort(phones);
                            Arrays.sort(phone);
                            for (String str : phones) {
                                if (Arrays.binarySearch(phone, str) < 0) {
                                    logger.debug("未发送成功的号码=================" + str);
                                    sb.append(str + "#");
                                }
                            }
                            // 发送的号码
                            if (sb.length() > 0) {
                                sendPhone = sb.toString();
                                sendPhone = sendPhone.substring(0, sendPhone.length() - 1);
                            }
                            
                            // 发送失败的号码判断
                            if (!"".equals(sendPhone) && !"".equals(business.getShopName())
                                    && business.getShopName() != null) {
                                // 短信平台发送短信=============================================
                                // 1.3.1根据转账id查询转账金额
                                Cbabill bill = cbabillMapper.selectByPrimaryKey(Long.parseLong(smsl.getBillId()));
                                Double amount = bill.getAmount();   //转账金额
                                String content = "[" + business.getShopName() + "]" + " Please be advised you have AU $" + amount
                                        + " through CBA transfer to your,please check. http://mmobile.e-swipe.com.au/ . " + Constants.SMS_LAST_STR;
                                if (sendPhone.contains("#")) {
                                    String sendphone[] = sendPhone.split("#");
                                    if (sendphone.length == 2) {
                                        smsService.sendBatchEventMessage(sendphone[0], sendphone[0], sendphone[1], null, null, content);
                                        
                                    } else if (sendphone.length == 3) {
                                        smsService.sendBatchEventMessage(sendphone[0], sendphone[0], sendphone[1], sendphone[2], null, content);
                                        
                                    } else if (sendphone.length == 4) {
                                        smsService.sendBatchEventMessage(sendphone[0], sendphone[0], sendphone[1], sendphone[2], sendphone[3], content);
                                    }
                                } else {
                                    smsService.sendBatchEventMessage(sendPhone, sendPhone, null, null, null, content);
                                }
                                logger.debug("短信发送内容=====================================" + content);
                                // 短信平台发送短信=============================================
                            }
                        }
                        for(PushSmsLog smsg : smslogl){
                            map.clear();
                            map.put("orderNo", smsg.getOrderNo());
                            map.put("type", 2);
                            // 1.2查询短信发送信息
                            List<PushSms> sms1 = pushSmsMapper.getPushsSmsByOrderNoAndType(map);
                            // 1.6获取商家的所有手机号和手机号的数量
                            String[] phones1 = {};
                            if (business.getPhone2() != null && !"".equals(business.getPhone2()) && !"".equals(business.getShopName())
                                    && business.getShopName() != null) {
                                phones = insert(phones, business.getPhone2());
                                if (StringUtils.isNotEmpty(business.getPhone3())) {// 大陆商家
                                    phones1 = insert(phones, business.getPhone3());
                                    if (StringUtils.isNotEmpty(business.getPhone4())) {
                                        phones1 = insert(phones, business.getPhone4());
                                    }
                                    if (StringUtils.isNotEmpty(business.getPhone5())) {
                                        phones1 = insert(phones, business.getPhone5());
                                    }
                                }
                            }
                            logger.debug("部分推送成功，则只推送失败的号码========================");
                            String sendPhone1 = "";
                            String[] phone1 = {};
                            StringBuffer sb1 = new StringBuffer();
                            if (sms1.size() > 0) {
                                for (int i = 0; i < sms1.size(); i++) {
                                    if (sms1.get(i).getStatus() == 1) {  // 成功的
                                        phone1 = insert(phone, sms1.get(i).getPhone());
                                        logger.debug("已发送成功的号码=================" + sms1.get(i).getPhone());
                                    }
                                }
                                // 对比前需要对数组进行排序
                                Arrays.sort(phones1);
                                Arrays.sort(phone1);
                                for (String str : phones1) {
                                    if (Arrays.binarySearch(phone1, str) < 0) {
                                        logger.debug("未发送成功的号码=================" + str);
                                        sb1.append(str + "#");
                                    }
                                }
                                // 发送的号码
                                if (sb1.length() > 0) {
                                    sendPhone1 = sb1.toString();
                                    sendPhone1 = sendPhone1.substring(0, sendPhone1.length() - 1);
                                }
                                // 发送失败的号码判断
                                if (!"".equals(sendPhone1) && !"".equals(business.getShopName())
                                        && business.getShopName() != null) {
                                    // 短信平台发送短信=============================================
                                    // 1.3.1批量修改订单发送情况
                                    if (sendPhone1.contains("#")) {
                                        String sendphone[] = sendPhone1.split("#");
                                        //修改短信发送情况和短信详情信息
                                        smsg.setTransferpushStatus(1); // 推送转账改为成功
                                        smsg.setTransferSmsStatus(2);  // 短信发送情况全部完成
                                        pushSmsLogMapper.updateByPrimaryKey(smsg);
                                        for (int i = 0; i < sendphone.length; i++) {
                                            map.clear();
                                            map.put("orderNo", smsg.getOrderNo());   // 订单号
                                            map.put("phone", sendphone[i]);
                                            map.put("type", 2);  // 转账短信
                                            PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                            if (osms == null) {  // 如果为空则新增保存
                                                PushSms sm = new PushSms();
                                                sm.setOrderNo(smsg.getOrderNo());
                                                sm.setType(2);
                                                sm.setStatus(1);
                                                sm.setSendTime(new Date());
                                                sm.setPhone(sendphone[i]);
                                                sm.setBillId(smsl.getBillId());
                                                pushSmsMapper.insertSelective(sm);
                                            } else {
                                                osms.setSendTime(new Date());  // 更新发送时间
                                                osms.setStatus(1);
                                                pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                            }
                                        }
                                    } else {
                                        //修改短信发送情况和短信详情信息
                                        smsg.setTransferpushStatus(1); // 推送转账改为成功
                                        smsg.setTransferSmsStatus(2);  // 短信发送情况全部完成
                                        pushSmsLogMapper.updateByPrimaryKey(smsg);
                                        map.clear();
                                        map.put("orderNo", smsg.getOrderNo());   // 订单号
                                        map.put("phone", sendPhone);
                                        map.put("type", 2);  // 转账短信
                                        PushSms osms = pushSmsMapper.selectPushSms(map); // 条件查询短信信息
                                        if (osms == null) {  // 如果为空则新增保存
                                            PushSms sm = new PushSms();
                                            sm.setOrderNo(smsg.getOrderNo());
                                            sm.setType(2);
                                            sm.setStatus(1);
                                            sm.setSendTime(new Date());
                                            sm.setPhone(sendPhone);
                                            sm.setBillId(smsl.getBillId());
                                            pushSmsMapper.insertSelective(sm);
                                        } else {
                                            osms.setSendTime(new Date());  // 更新发送时间
                                            osms.setStatus(1);
                                            pushSmsMapper.updateByPrimaryKey(osms);   // 更新短信发送信息
                                        }
                                    }
                                    // 短信平台发送短信=============================================
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("转账定时任务失败=======",e);
        }
    }
 
    
    
    private static String[] insert(String[] arr, String str){
        int size = arr.length;
        String[] tmp = new String[size + 1];
        System.arraycopy(arr, 0, tmp, 0, size);
        tmp[size] = str;
        return tmp;
    }
    
}
